package com.qingxin.sys.tag;

import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.service.SysPermissionService;
import com.qingxin.sys.service.SysUserService;
import com.qingxin.sys.support.SystemCfg;

/**
 * 权限控制标签，有权限时输出标签内容，否则忽略标签内容
 * @author Administrator
 *
 */
public class PermissionTag extends BodyTagSupport {
	private static final long serialVersionUID = -7009664165965972036L;

	private String code;
	
	public int doStartTag() throws JspException {
		if(code == null){
			code = null;
			return SKIP_BODY;
		}
		
		String userid = (String) pageContext.getSession().getAttribute(SystemCfg.SESSION_LOGIN_USERID);
		if(userid == null){
			code = null;
			return SKIP_BODY;
		}
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
		SysUserService sysUserService = context.getBean(SysUserService.class);
		LoginUser loginUser = sysUserService.getLoginUser(userid);
		if(loginUser==null){
			code = null;
			return SKIP_BODY;
		}
		if(SystemCfg.isSystemAdminUser(loginUser)){
			code = null;
			return EVAL_BODY_INCLUDE;
		}
		if(SystemCfg.isAdminUser(loginUser)){
			code = null;
			return EVAL_BODY_INCLUDE;
		}
		SysPermissionService sysPermissionService = context.getBean(SysPermissionService.class);
		Set<String> rights = sysPermissionService.getUserPermissionCodes(userid);
		if(rights.contains(code.toUpperCase())){
			code = null;
			return EVAL_BODY_INCLUDE;
		}
		code = null;
		return SKIP_BODY;//无权限
	}
	
	
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	
}
